﻿#include "XQSplitterWidget.h"
#include"QMessageBox"
#include<QDebug>
XQSplitterWidget::XQSplitterWidget(QWidget* parent)
	:QSplitter(parent)
{

}

XQSplitterWidget::~XQSplitterWidget()
{
}

void XQSplitterWidget::setWidgetWidthRatio(const QList<int>& list)
{
	m_WidgetWidthRatio = list;
	setSizes(WidgetWidthRatio());
}

void XQSplitterWidget::HiddenDisplayWidget(const size_t index)
{
	QList<int> current= sizes();

	size_t zeroCount = 0;
	for (size_t i = 0; i < current.size(); i++)
	{
		if (current[i] == 0)
		{
			++zeroCount;
		}
		/*if (i != index)
		{
			m_SpEditlSize[i] = current[i];
		}*/
	}

	if (current[index] != 0)//将他隐藏
	{
		if (zeroCount == current.size() - 1)
		{
			QMessageBox::information(this,"提示","最后一个不允许隐藏！");
			return;
		}
		m_MaxWidth[index] =widget(index)->maximumWidth();//保存最大宽度
		widget(index)->setMaximumWidth(0);
		m_SpEditlSize= current;
		//qInfo() << m_SpEditlSize[index];
		int temp = m_SpEditlSize[index];
		m_SpEditlSize[index] = 0;
		setSizes(m_SpEditlSize);
		m_SpEditlSize[index] = temp;
		WidgetWidthZero(index);
		return;
	}
	
	if (m_SpEditlSize[index] == 0)//现在和记录都是零，将其设定为默认值了
	{
		m_SpEditlSize[index] = WidgetWidthRatio()[index];
	}
	widget(index)->setMaximumWidth(m_MaxWidth[index]);
	setSizes(m_SpEditlSize);
}

void XQSplitterWidget::addWidget(QWidget* widget)
{
	QSplitter::addWidget(widget);
	if (m_WidgetWidthRatio.size() < sizes().size())
	{
		m_WidgetWidthRatio.append(1);
		m_MaxWidth.append(widget->maximumWidth());
	}
}

int XQSplitterWidget::widgetWidth(const size_t index)
{
	return sizes()[index];
}

QList<int> XQSplitterWidget::WidgetWidthRatio()
{
	int sum = 0;
	for (auto& n : m_WidgetWidthRatio)
	{
		sum += n;
	}
	int w = size().width();
	QList<int> newSizes;
	for (size_t i = 0; i < m_WidgetWidthRatio.size(); i++)
	{
		newSizes.append(w / sum * m_WidgetWidthRatio[i]);
	}
	return newSizes;
}

void XQSplitterWidget::showEvent(QShowEvent* event)
{
	m_SpEditlSize= sizes();
	setWidgetWidthRatio(m_WidgetWidthRatio);
	for (size_t i=0;i<m_WidgetWidthRatio.size();i++)
	{
		setStretchFactor(i, m_WidgetWidthRatio[i]);
	}
}
